//
//  ProviderDelegate.m
//  VoIPTest
//
//  Created by 王大虎 on 2022/8/22.
//  Copyright © 2022 oopsr. All rights reserved.
//

#import "ProviderDelegateTest.h"
#import <AVFoundation/AVFAudio.h>

#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width


#import <JitsiMeetSDK/JitsiMeetSDK-Swift.h>
#import <WebRTC/WebRTC.h>
#import "CustomView.h"


@interface ProviderDelegateTest ()

@property (nonatomic ,strong) CXProvider *provider;
@property (nonatomic, assign) BOOL isAudioMuted;

@property (nonatomic, strong) CallManager *callManager;
@property (nonatomic, strong) NSString *roomName;
@property (nonatomic, assign) BOOL isViewPresenting;
@property (nonatomic, strong) CustomView *customView;




@end
@implementation ProviderDelegateTest

static ProviderDelegateTest *shared = nil;

- (instancetype)initWithCallManager:(CallManager *)callManager
{
    self.callManager = callManager;
    self = [super init];
    if (self) {
        self.roomName = @"SampleJitsiAppRoom101";
        
        //用一个 CXProviderConfiguration 初始化 CXProvider，前者在后面会定义成一个静态属性。CXProviderConfiguration 用于定义通话的行为和能力。
        self.provider = [[CXProvider alloc]initWithConfiguration:self.config];
        //为了能够响应来自于 CXProvider 的事件，你需要设置它的委托。
        [self.provider setDelegate:self queue:nil];
    }
    return self;
}


+(void)configureAudioSession{
    NSLog(@"Callkit& Configuring audio session");
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [session setMode:AVAudioSessionModeVoiceChat error:nil];
}

//通过设置CXProviderConfiguration来支持视频通话、电话号码处理，并将通话群组的数字限制为 1 个，其实光看属性名大家也能看得懂吧。
- (CXProviderConfiguration *)config{
    static CXProviderConfiguration* configInternal = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        configInternal = [[CXProviderConfiguration alloc] initWithLocalizedName:@"我的"];
        configInternal.supportsVideo = NO;
        configInternal.maximumCallsPerCallGroup = 1;
        configInternal.maximumCallGroups = 1;
        configInternal.supportedHandleTypes = [NSSet setWithObject:@(CXHandleTypePhoneNumber)];
        UIImage* iconMaskImage = [UIImage imageNamed:@"IconMask"];
        configInternal.iconTemplateImageData = UIImagePNGRepresentation(iconMaskImage);
        configInternal.ringtoneSound = @"voip_call.caf";
    });
    
    return configInternal;
}


//这个方法牛逼了，它是用来更新系统电话属性的。。
-(CXCallUpdate *)callUpdate:(NSString *)handle andHasVideo:(BOOL)hasVideo{
    CXCallUpdate *update = [[CXCallUpdate alloc]init];
    update.localizedCallerName = @"aaaaaaaa";
    update.supportsGrouping = NO;
    update.supportsHolding = NO;
    update.remoteHandle = [[CXHandle alloc] initWithType:CXHandleTypePhoneNumber value:handle];
    update.hasVideo = hasVideo;
    return update;
}

- (void)providerDidReset:(nonnull CXProvider *)provider {

}

- (void)provider:(CXProvider *)provider performStartCallAction:(CXStartCallAction *)action{
    //向系统通讯录更新通话记录
    CXCallUpdate *update = [self callUpdate:action.handle.value andHasVideo:action.isVideo];
    [provider reportCallWithUUID:action.callUUID updated:update];
  
    [action fulfill];

    
}

//打电话方法
-(void)reportIncomingCall:(NSUUID *)uuid andHandle:(NSString *)handle andHasvideo:(BOOL)hasVideo andCompletion:(completion2)completion{
    CXCallUpdate *update = [self callUpdate:handle andHasVideo:hasVideo];
    
    [self.provider reportNewIncomingCallWithUUID:uuid update:update completion:^(NSError * _Nullable error) {
        if (nil == error) {
            Call *call = [[Call alloc]initWithUUID:uuid isOutgoing:NO handle:handle isAudioCall:YES];
            [self.callManager add:call];
        }
        completion(error);
    }];
}
 
//接电话（按钮的返回）
- (void)provider:(CXProvider *)provider performAnswerCallAction:(CXAnswerCallAction *)action{
   
    [ProviderDelegateTest configureAudioSession];
   

    [action fulfill];

}

//挂电话的按钮，点击事件
- (void)provider:(CXProvider *)provider performEndCallAction:(CXEndCallAction *)action{

    //在这里添加自己App挂断电话的逻辑
    [action fulfill];
}

- (void)provider:(CXProvider *)provider performSetHeldCallAction:(CXSetHeldCallAction *)action{
    
    
    [action fulfill];
}

- (void)provider:(CXProvider *)provider didActivateAudioSession:(AVAudioSession *)audioSession{
    [self showJitsiView];
}



-(void)showJitsiView{
    CustomView *customView = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    customView.callManager = self.callManager;
    customView.roomName = self.roomName;
    Call *cc = self.callManager.calls[0];
    customView.call = [self.callManager callWithUUID:cc.uuid];
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow  addSubview:customView];
    [customView joinMeet];
}
@end
